from django.shortcuts import render,redirect
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse,StreamingHttpResponse
from django import forms
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.core.paginator import Paginator
from .models import SignIn,Course,Tinfo,Zuoyefb,Zuoyetj,Stucourse,Qiandao,Grade,Liuyan,Rank,Resource,Test,Verify,Exam,Gonggao,Teaproc,Stuproc,Tpcourse,Ctime,Sinfo
import re,datetime,time,os,string,math,json,pandas,xlwt
from io import StringIO,BytesIO

import pandas as pd
#coding:utf-8


# Create your views here.
#用户登录表单
class UserForm(forms.Form):
    userid = forms.CharField(label='用 户 名', max_length=100)
    password = forms.CharField(label='密___码', widget=forms.PasswordInput())

#注册表单
class UserForm1(UserForm):
    rePassword=forms.CharField(label='确认密码',widget=forms.PasswordInput(),max_length=100)
#教师作业发布表单
class ZuoyeForm(forms.Form):
    zy_topic=forms.CharField()
    zy_text=forms.CharField()

#学生提交作业表单
class ZuoyetjForm(ZuoyeForm):
    ttopic=forms.CharField()
    zy_upload=forms.FileField()
#教师发布考试信息表单
#此处用到form表单中ChoiceField()下拉菜单 动态展示数据库【类似于H5 selector下拉菜单】
class TestForm(forms.Form):
    paper=forms.FileField()
    cname=forms.ChoiceField(label=u'课程名')
    def __init__(self,tnm):
        super(TestForm, self).__init__()
        self.fields['cname'].choices=((x.id,x.cname) for x in Tpcourse.objects.filter(
            tname__tname=tnm))

#登录
def login(request):
    pattern = r'^[a-zA-Z0-9_-]+@hpu.edu.cn$'
    if request.method == 'POST':

        uf = UserForm(request.POST)
        if uf.is_valid():
            # 获取表单用户密码
            userid = uf.cleaned_data['userid']
            password = uf.cleaned_data['password']
            # 获取的表单数据与数据库进行比较
            user = SignIn.objects.filter(id__exact=userid, pw__exact=password)
            if user:
                # 比较成功，跳转index
                if re.match(pattern,userid):
                    response = HttpResponseRedirect('/teaIndex/')
                    # 将username写入浏览器cookie,失效时间为3600
                else:
                    response = HttpResponseRedirect('/stuIndex/')
                    # 将username写入浏览器cookie,失效时间为3600
                response.set_cookie('userid', userid)
                return response
            else:

                # 比较失败，还在login
                request.session['error']=1
                # return HttpResponseRedirect('/')
    else:
        request.session['error'] = 0
        uf = UserForm()

    return render(request,'login.html', context={'uf': uf})

#注册
def regist(request):
    if request.method == 'POST':
        uf = UserForm1(request.POST)
        if uf.is_valid():
            # 获得表单数据
            userid = uf.cleaned_data['userid']
            password = uf.cleaned_data['password']
            user = SignIn.objects.filter(id__exact=userid)
            if user:
                return HttpResponseRedirect('/regist/')
            if uf.cleaned_data['rePassword']==password:
                # 添加到数据库
                SignIn.objects.create(id=userid, pw=password)
                return HttpResponseRedirect('/')
    else:
        uf = UserForm1()
    return render(request,'login.html', {'uf': uf})

#学生主界面
def stuIndex(request):
    userid=request.COOKIES.get('userid')
    cnumList=Stucourse.objects.filter(snum__id=userid)
    image= Sinfo.objects.get(snum__id=userid).simage
    name=Sinfo.objects.get(snum__id=userid).sname
    request.session['name']=name
    request.session['image']=str(image)
    course=[]
    examtips=[]
    for c in cnumList:
        cn=Tpcourse.objects.filter(id=c.cnum_id)
        tips=Exam.objects.filter(examname=cn[0].cname)
        examtips.append(tips)
        course.append(cn[0].cname)
    gg=Gonggao.objects.all().order_by('-gtime')
    return render(request,'stuIndex.html',{'userid':userid,'course':course,'examtips':examtips,
                                           'gonggao':gg})

def skebiao(request):
    userid = request.COOKIES.get('userid')
    cous=Stuproc.objects.filter(snum__id=userid)

    return render(request,'skebiao.html',{'cous':cous})

#学生选课
def xuanke(request):
    userid = request.COOKIES.get('userid')
    cn = Tpcourse.objects.filter()

    return render(request, 'xuake.html', {'cn': cn})

def course(request):
    snum=request.COOKIES.get('userid')
    cids=request.GET.get('cid')
    print(cids)
    idlist=cids.split('_')
    flag=0
    for s in idlist:
        if Stucourse.objects.filter(cnum_id=int(s),snum_id=snum):
            flag=1
            continue
        else:
            Stucourse.objects.create(cnum_id=int(s),snum_id=snum)
    courses=Stucourse.objects.filter(snum__id=snum)
    return render(request,'course.html',{'courses':courses,'flag':flag})

def ctable(request):
    snum = request.COOKIES.get('userid')
    pids = request.GET.get('pid')
    print(pids)
    idlist = pids.split('_')
    print(idlist)
    flag = 0
    dict={}
    if idlist:
        for s in idlist:
            if Stuproc.objects.filter(pid_id=int(s),snum__id=snum):
                flag = 1
                continue
            else:
                Stuproc.objects.create(pid_id=int(s), snum_id=snum)
    dict['flag']=flag
    return JsonResponse(dict)
    # return HttpResponseRedirect('/xuanke/ctable')

#学生公告
def gonggao(request):
    tip=request.GET.get('tip')
    if tip.isdigit():
        print('xxx')
        detail=Gonggao.objects.filter(id=tip)
    else:
        print('yyy')
        detail=Exam.objects.filter(examname=tip)
    return render(request,'gonggao.html',{'detail':detail})
#学生。成绩
def stuGrade(request):
    userid = request.COOKIES.get('userid')
    cnumList=Stucourse.objects.filter(snum__id=userid).order_by('cnum_id')
    full=[]
    cn = [c.cnum_id for c in cnumList]

    g=Grade.objects.filter(snum=userid).filter(cnum__in=cn)
    if g:
        #print('xxx')
        for i in g:
            y=0
            sub = []
            grade=i.finalgrade
            #print(grade)
            grades = Grade.objects.filter(cnum=i.cnum).order_by('-finalgrade')
            for x in grades:
                y+=1
                if x.finalgrade==grade:
                    break
            #print(y)
            rank = Rank.objects.filter(cnum_id=i.cnum)
            sub.append(rank)
            sub.append(grade)
            sub.append(y)
            full.append(sub)
    return render(request,'stuGrade.html',{'full':full})
#学生.课程主界面
def stuTask(request,page=1):
    cname = request.GET.get('cname')
    request.session['cname']=cname
    userid=request.COOKIES.get('userid')
    cnum=Stucourse.objects.filter(snum_id=userid,cnum__cname=cname)
    print(cnum[0].cnum_id)
    liuyan = Liuyan.objects.filter(cnum=cnum[0].cnum_id).filter(snum=userid).order_by('-lytime')
    pg = Paginator(liuyan, 4)
    p = pg.page(page)
    source = Resource.objects.filter(cname=cname).order_by('-sctime')
    if request.method == 'POST':
        post = request.POST
        title=post.get('title','')
        content = post.get('content')
        now = datetime.datetime.now()
        Liuyan.objects.create(lytext=content, title=title, cname=cname,
                              lytime=now, snum=userid)

    return render(request, 'stuTask.html', {'liuyan':liuyan,'p':p,'pg':pg,'source':source,'divqd':1})

#评论互动展示
def ly(request):
    lyid=request.GET.get('tid')
    cname=request.session.get('cname')
    userid = request.COOKIES.get('userid')
    title=Liuyan.objects.get(id=lyid).title
    if request.method=='POST':
        post=request.POST
        content=post.get('text','')
        now=datetime.datetime.now()

        Liuyan.objects.create(lytext=content, title=title,cname=cname,
                                         lytime= now,snum=userid)
    if str(userid).split('@')[-1]=='hpu.edu.cn':
        li='<li><a href="/teaIndex">返&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;回</a></li>'
    else:
        li='<li><a href="/stuIndex/stuTask?cname=%s">返&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;回</a></li><li><a href="#">&#10047;&#10047;&#10047;&#10047;</a></li><li><a href="#">&#10047;&#10047;&#10047;&#10047;</a></li>'%cname
    detail=Liuyan.objects.filter(title=title).order_by('lytime')
    return render(request,'ly.html',{'detail':detail,'title':title,'cname':cname,'li':li})

#学生.签到
def qiandao_ajax(request):
    cname = request.session.get('cname')
    userid = request.COOKIES.get('userid')
    sname = request.session.get('name')
    now = datetime.datetime.now()
    dict={}
    if Qiandao.objects.filter(cname=cname, snum=userid):
        Qiandao.objects.filter(cname=cname, snum=userid).order_by('signtime')
        lastime=Qiandao.objects.filter(cname=cname, snum=userid).latest('signtime').signtime
        lastamp = datetime.datetime.strptime(lastime.strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d "
                                                                                 "%H:%M:%S")
        u=now-lastamp
        if u>datetime.timedelta(hours=12):
            Qiandao.objects.create(cname=cname, snum=userid, sname=sname, signtime=now,flag=1)
            msg = '签到成功！'
        else:
            msg = '您已签到，不能重复签到！'
    else:
        Qiandao.objects.create(cname=cname, snum=userid, sname=sname, signtime=now,flag=1)
        msg='签到成功！'
    dict['msg']=msg
    return JsonResponse(dict)

#学生.作业管理
def zuoyetj(request,page=1):
    userid = request.COOKIES.get('userid')
    cname = request.session.get('cname')
    sname=Sinfo.objects.get(snum__id=userid).sname
    if request.method=='POST':
        post = request.POST
        zyupload = request.FILES.get('zy_upload')
        tjtext = post.get('zy_text')
        topic = post.get('ttopic')
        now=datetime.datetime.now()
        Zuoyetj.objects.get_or_create(snum=userid,sname=sname,fbtext=topic,cname=cname,defaults={'tjtime':now.strftime('%Y-%m-%d %H:%M:%S'),'tjtext':tjtext,'filepath':zyupload})
        return HttpResponseRedirect('/stuIndex/stuTask/zuoyetj')
    fb_text = Zuoyefb.objects.filter(course=cname)
    pg = Paginator(fb_text, 10)
    p = pg.page(page)
    return render(request, 'zuoyetj.html', {'fb_text': fb_text,'pg':pg,'p':p})

#学生查看作业时的ajax
def ajax_tjstu(request):
    userid = request.COOKIES.get('userid')
    zytopic=request.GET.get('zytopic')
    print(zytopic)
    fbt=Zuoyefb.objects.get(zytopic=zytopic).fbtext
    dict={}
    if Zuoyetj.objects.filter(fbtext=zytopic,snum=userid):
        tjtime = Zuoyetj.objects.get(fbtext=zytopic, snum=userid).tjtime
        tjtext = Zuoyetj.objects.get(fbtext=zytopic, snum=userid).tjtext
        filepath=Zuoyetj.objects.get(fbtext=zytopic, snum=userid).filepath
        dict['tjtime'] = tjtime

        dict['fbtext'] = zytopic
        if tjtext:
            dict['tjtext'] = tjtext
        else :
            dict['tjtext'] = ''
        if filepath:
            dict['filepath']=str(filepath)
        else:
            dict['filepath'] = ''
    else:
        dict['tjtime'] = ''
        dict['tjtext'] = ''
        dict['fbtext'] = zytopic
        dict['fbt']=fbt
        dict['filepath'] = ''
    print(dict)
    return JsonResponse(dict)

#教师主界面
def teaIndex(request,page=1):
    userid=request.COOKIES.get('userid')
    tname=Tinfo.objects.get(email=userid).tname
    image=Tinfo.objects.get(email=userid).image
    request.session['name']=tname
    request.session['image']=str(image)

    courses=Tpcourse.objects.filter(tname__tname=tname)
    cList=[c.cname for c in courses]
    cnumList=[cn.id for cn in courses]

    liuyan = Liuyan.objects.filter(cnum__in=cnumList).order_by('-lytime')
    pg = Paginator(liuyan, 10)
    p = pg.page(page)
    return render(request,'teaIndex.html',{'course':courses,
                                           'liuyan':liuyan,'p':p,'pg':pg})

#教师.教学日历

def change(request):
    userid=request.COOKIES.get('userid')
    str='@hpu.edu.cn'
    print('xx')
    if str==userid[-11:]:
        flag=1
        name=Tinfo.objects.get(email=userid).tname
    else:
        name=Sinfo.objects.get(snum__id=userid).sname
        flag=0
    return render(request,'change.html',{'userid':userid,'name':name,'flag':flag})

@csrf_exempt
def info_ajax(request):
    userid = request.COOKIES.get('userid')
    post=request.POST
    opw=post.get('opw')
    npw1=post.get('npw1')
    try:
        list=SignIn.objects.get(id=userid)

        if list.pw==opw:

            list.pw=npw1
            list.save()
            tip = 1
        else:
            tip=0
    except Exception as e:
        print(e)
        tip=3
    return JsonResponse({'tip':tip})


def tcallendar(request):
    userid = request.COOKIES.get('userid')
    tname = Tinfo.objects.get(email=userid).tname
    course = Tpcourse.objects.filter(tname__tname=tname)
    return render(request,'tcallendar.html',{'course':course})

#教师.教学日历.ajax【日历控件】
def event_ajax(request):
    dates=request.GET.get('date')
    userid = request.COOKIES.get('userid')
    tname = Tinfo.objects.get(email=userid).tname
    course = Tpcourse.objects.filter(tname__tname=tname)
    cn=[c.id for c in course]

    t = datetime.datetime.strptime(dates, "%Y-%m-%d").isocalendar()
    week=t[2]
    print(week)
    nw= Teaproc.objects.filter(week=week).filter(cnum__in=cn)
    sery = serializers.serialize('json',nw)
    flags={}
    # for i in range(0,7):
    #     tp=Teaproc.objects.filter(week=(week+i)%7)
    #     if tp:
    #         flags[i]=1
    #     else:
    #         flags[i]=0
    flags['ss']=sery
    print(flags)
    return JsonResponse(flags,safe=False)

def jxrili_ajax(request):
    dates = request.GET.get('date')
    userid = request.COOKIES.get('userid')
    tname = Tinfo.objects.get(email=userid).tname
    course = Tpcourse.objects.filter(tname__tname=tname)
    temp=Course.objects.filter(id=1)
    startdate=temp[0].kkdate.isocalendar()
    startweek=startdate[1]
    t = datetime.datetime.strptime(dates, "%Y-%m-%d").isocalendar()
    currentweek = t[1]
    c=currentweek-startweek
    flags = {}
    if c<20:
        weeklist = ['第一周', '第二周', '第三周', '第四周', '第五周', '第六周', '第七周', '第八周', '第九周', '第十周', '第十一周','第十二周', '第十三周', '第十四周', '第十五周', '第十六周', '第十七周', '第十八周', '第十九周', '第二十周']
        cweek=weeklist[c]
        #print(cweek)
        cn = [c.id for c in course]
        detail=Ctime.objects.filter(cweek=cweek).filter(cnum__in=cn)
        #print(cn)
        sery = serializers.serialize('json', detail)

        flags['ss'] = sery
        #print(flags)
    else:
        flags['ss']=''
    print(flags)
    return JsonResponse(flags,safe=False)
def teapick(request):
    cn = Course.objects.filter()
    return render(request,'teapick.html',{'cn':cn})

def picknext(request):
    userid = request.COOKIES.get('userid')
    tname = Tinfo.objects.get(email=userid).tname
    pids = request.GET.get('pid')
    print(pids)
    idlist = pids.split('_')
    print(idlist)
    flag = 0
    dict = {}
    if idlist:
        for s in idlist:
            cList=Course.objects.filter(id=int(s))
            cname=cList[0].cname

            if Tpcourse.objects.filter(cname=cname,tname__tname=tname):
                flag = 1
                continue
            else:
                Tpcourse.objects.create(cname=cname,tname=Tinfo.objects.get(tname=tname))
    dict['flag'] = flag
    print(dict)
    return JsonResponse(dict)
#教师.课程主界面
def teaTask(request):
    cname=request.GET.get('cname')
    request.session['cname']=cname
    request.session.get('qdtime')
    if request.method=='POST':
        post = request.POST
        upre = request.FILES.get('upre','')
        abstract = post.get('abstract')
        now=datetime.datetime.now()
        Resource.objects.create(sctime=now.strftime('%Y-%m-%d %H:%M:%S'), abstract=abstract,
                                scfp=upre ,cname=cname)
    source = Resource.objects.filter(cname=cname).order_by('-sctime')
    return render(request,'teaTask.html',{'cname':cname,'source':source,'divqd':1})

#教师.学生成绩单/名单
def detail(request):
    userid = request.COOKIES.get('userid')
    cname=request.session.get('cname')
    tname = Tinfo.objects.get(email=userid).tname
    cnum = Tpcourse.objects.get(cname=cname, tname__tname=tname).id
    val=request.GET.get('val')
    dict={}
    if val=='chengjidan':

        gra=Grade.objects.filter(cnum=cnum)
        rank=Rank.objects.filter(cnum_id=cnum)
        dict['info']=gra
        dict['rank']=rank
        dict['flag']=1
    else:
        sinfo = Stucourse.objects.filter(cnum_id=cnum).order_by('snum_id')
        dict['info']=sinfo
        dict['flag']=0
    #print(dict)
    dict['cname']=cname
    return render(request,'detail.html',dict)

def cdetail(request):
    weeklist=['第一周','第二周','第三周','第四周','第五周','第六周','第七周','第八周','第九周','第十周','第十一周','第十二周','第十三周','第十四周','第十五周','第十六周','第十七周','第十八周','第十九周','第二十周']
    userid = request.COOKIES.get('userid')
    cname = request.session.get('cname')
    tname = Tinfo.objects.get(email=userid).tname
    cnum=Tpcourse.objects.get(cname=cname,tname__tname=tname).id
    for x in range(0,20):
        if Ctime.objects.filter(cweek=weeklist[x], cnum_id=cnum):
            continue
        else:
            Ctime.objects.create(cweek=weeklist[x], cnum_id=cnum, chours='',ctext='',catagory='')
    if request.method=='POST':
        post=request.POST
        jiaocai=post.get('book','')
        dagang=post.get('dagang','')
        keshi=post.get('keshi','')
        if jiaocai and dagang and keshi!='':
            Tpcourse.objects.filter(cname=cname,tname__tname=tname).update(jiaocai=jiaocai)
            Tpcourse.objects.filter(cname=cname,tname__tname=tname).update(dagang=dagang)
            Tpcourse.objects.filter(cname=cname,tname__tname=tname).update(keshi=keshi)
        first=Ctime.objects.filter(cnum_id=cnum).first()
        id=first.id
        for i in range(id,id+20):
            week='w%s'%i
            xueshi='x%s'%i
            text='t%s'%i
            cate='c%s'%i
            cweek=post.get(week,'')
            chour=post.get(xueshi,'')
            ctext=post.get(text,'')
            catagory=post.get(cate,'')

            if Ctime.objects.filter(cweek=cweek,cnum_id=cnum):
                Ctime.objects.filter(cweek=cweek,cnum_id=cnum).update(chours=chour)
                Ctime.objects.filter(cweek=cweek,cnum_id=cnum).update(ctext=ctext)
                Ctime.objects.filter(cweek=cweek,cnum_id=cnum).update(catagory=catagory)
            else:
                Ctime.objects.create(cweek=cweek,cnum_id=cnum,chours=chour,ctext=ctext,
                                     catagory=catagory)
    ctime = Ctime.objects.filter(cnum_id=cnum).order_by('id')
    return render(request,'cdetail.html',{'ctime':ctime})

#教师.课堂考勤.ajax【日历控件】
def qdshow(request):
    cname=request.session.get('cname')
    qdtime = request.GET.get('v')
    request.session['qdtime']=qdtime
    t=datetime.datetime.strptime(qdtime,"%Y-%m-%d %H:%M:%S")
    now=t.strftime("%Y-%m-%d %H:%M:%S")
    tt=t-datetime.timedelta(minutes=20)
    pre=tt.strftime("%Y-%m-%d %H:%M:%S")
    #获取指定时间前20分钟内的签到学生信息
    qd_list=Qiandao.objects.filter(signtime__lte=now).filter(signtime__gte=pre).filter(
        cname=cname).order_by('snum')
    dict = {}
    for x in range(0, len(qd_list)):
        dict['snum' + str(x)] = qd_list[x].snum
        dict['sname' + str(x)] = qd_list[x].sname
        dict['signtime' + str(x)] = qd_list[x].signtime
        Qiandao.objects.filter(snum=qd_list[x].snum,signtime=qd_list[x].signtime).update(flag=0)
    dict['len'] = len(qd_list)

    return JsonResponse(dict)

#教师.作业管理
def zuoye(request,page=1):
    userid = request.COOKIES.get('userid')
    cname = request.session.get('cname')
    tname = Tinfo.objects.get(email=userid).tname
    cnum = Tpcourse.objects.get(cname=cname, tname__tname=tname).id
    if request.method=='POST':
        zf=ZuoyeForm(request.POST)
        if zf.is_valid():
            # 获得表单数据
            zytopic=zf.cleaned_data['zy_topic']#dddddddd

            zytext = zf.cleaned_data['zy_text']
            now=datetime.datetime.now()
            # Zuoyefb.objects.create(fbtime=now,fbtext=zytext,course=cname,cnum=cnum)
            Zuoyefb.objects.create(fbtime=now, zytopic=zytopic,fbtext=zytext,course=cname,cnum=cnum)

        post = request.POST
        fbtxt=post.get('problem')
        tj_list=Zuoyetj.objects.filter(fbtext=fbtxt).order_by('snum')
        for i in range(0,len(tj_list)):
            pingfen=post.get(str(i))
            print(pingfen)
            Zuoyetj.objects.filter(snum=tj_list[i].snum,fbtext=fbtxt).update(pingfen=pingfen)
        return HttpResponseRedirect('/teaIndex/teaTask/zuoye')
    else:
        zf=ZuoyeForm()
    fb_text=Zuoyefb.objects.filter(cnum=cnum).order_by('fbtime')
    pg = Paginator(fb_text, 16)
    p = pg.page(page)
    return render(request,'zuoye.html',{'cname':cname,'zf':zf,'fb_text':fb_text,'pg':pg,'p':p})

#教师.作业批改（评分）.ajax
def ajax_tj(request):
    userid = request.COOKIES.get('userid')
    fbtext=request.GET.get('fbtext')
    tj=Zuoyetj.objects.filter(fbtext=fbtext).order_by('snum')
    dict={}
    for x in range(0,len(tj)):

        dict['snum'+str(x)]=tj[x].snum
        dict['sname'+str(x)]=tj[x].sname
        dict['tjtime'+str(x)]=tj[x].tjtime
        dict['tjtext'+str(x)]=tj[x].tjtext
        dict['filepath'+str(x)]=str(tj[x].filepath)
        dict['pingfen'+str(x)]=tj[x].pingfen
    dict['len']=len(tj)

    dict['fbtext']=fbtext
    return JsonResponse(dict)

#教师.（写入）成绩管理
def chengji(request):
    userid=request.COOKIES.get('userid')
    cname=request.session.get('cname')
    tname = Tinfo.objects.get(email=userid).tname
    cnum=Tpcourse.objects.get(cname=cname,tname__tname=tname).id
    print(cnum)
    sinfo=Stucourse.objects.filter(cnum_id=cnum).order_by('snum_id')
    zycnt=Zuoyefb.objects.filter(cnum=cnum).count()
    print(zycnt)
    testcnt=len(sinfo)
    for i in sinfo:
        snum=i.snum_id
        sname=Sinfo.objects.get(snum__id=snum).sname
        counts=Qiandao.objects.filter(cname=cname,snum=snum,flag=0).count()

        zy_grades=Zuoyetj.objects.filter(cname=cname,snum=snum)
        grade =0.0
        for j in zy_grades:
           # print(j.pingfen)
            grade=grade+j.pingfen
            #print('1')
        g=grade/zycnt
        if Grade.objects.filter(snum=snum,cname=cname,cnum=cnum):
            Grade.objects.filter(snum=snum, cname=cname, cnum=cnum).update(qdcont=counts)
            Grade.objects.filter(snum=snum, cname=cname, cnum=cnum).update(zygrades=g)
            Grade.objects.filter(snum=snum, cname=cname, cnum=cnum).update(sname=sname)
        else:
            Grade.objects.create(snum=snum,cname=cname,cnum=cnum,qdcont=counts,zygrades=g,
                                 sname=sname)
    grages=Grade.objects.filter(cnum=cnum)
    #按教师选择考试占比并根据所输入的平时/考试成绩 计算最终成绩
    if request.method=='POST':
        post=request.POST
        opt=request.session.get('option')
        u=opt.split(':')[0]
        t=opt.split(':')[-1]
        for j in grages:
            uname='u%s'%(j.snum)
            tname='t%s'%(j.snum)
            usualgrade=post.get(uname,'')
            testgrade=post.get(tname,'')
            if usualgrade =='':
                usual=0
            else:
                usual=int(usualgrade)*int(u)/10
            if testgrade=='':
                test=0
            else:
                test=(int(testgrade)*int(t))/10
            final=test+usual
            Grade.objects.filter(snum=j.snum,cnum=j.cnum).update(usualgrade=usual)
            Grade.objects.filter(snum=j.snum,cnum=j.cnum).update(testgrade=test)
            Grade.objects.filter(snum=j.snum,cnum=j.cnum).update(finalgrade=final)
    #统计该课程学生成绩综合情况（最高分，最低分，平均分）
        h = Grade.objects.filter(cnum=cnum).order_by('-finalgrade')
        l = Grade.objects.filter(cnum=cnum).order_by('finalgrade')
        level1=Grade.objects.filter(cnum=cnum).filter(finalgrade__lte=100).filter(
            finalgrade__gte=85).count()
        level2=Grade.objects.filter(cnum=cnum).filter(finalgrade__lte=84).filter(
            finalgrade__gte=70).count()
        level3=Grade.objects.filter(cnum=cnum).filter(finalgrade__lte=69).filter(
            finalgrade__gte=60).count()
        level4=Grade.objects.filter(cnum=cnum).filter(finalgrade__lte=59).count()
        sumGrade = 0
        for i in h:
            sumGrade = sumGrade + i.finalgrade
        ave=sumGrade/testcnt
        high=h[0].finalgrade
        low=l[0].finalgrade

        if Rank.objects.filter(cnum_id=cnum,cname=cname):

            Rank.objects.filter(cnum_id=cnum, cname=cname).update(high=high)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(level1=level1)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(level2=level2)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(level3=level3)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(level4=level4)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(rate=opt)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(low=low)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(testcnt=testcnt)
            Rank.objects.filter(cnum_id=cnum, cname=cname).update(ave=ave)
        else:
            Rank.objects.create(cnum_id=cnum,cname=cname,high=high,low=low,testcnt=testcnt,
                                ave=ave,rate=opt,level1=level1,level2=level2,level3=level3,level4=level4)
        return HttpResponseRedirect('/teaIndex/teaTask/chengji')
    gra=Grade.objects.filter(cnum=cnum).order_by('snum')
    return render(request,'chengji.html',{'grades':grages,'gra':gra})

#获取chengji.html通过ajax传来selector.options【获取所选比例】
def select(request):
    opt=request.GET.get('opt')
    request.session['option']=opt
    print(opt)
    return JsonResponse({'i':0})

#教师.考试管理
def test(request):
    userid = request.COOKIES.get('userid')
    tname = Tinfo.objects.get(email=userid).tname

    if request.method == 'POST':
        #此处用到根据查询数据库动态显示下拉菜单【该教师所教课程】
        tf = TestForm(tname)
        x=request.FILES.get('paper')
        y=request.POST.get('cname')
        cnum=Tpcourse.objects.filter(id=y)
        if cnum:
            cnm=cnum[0].cname
            print(x,y)
            if Test.objects.filter(cnm=cnm):
                Test.objects.filter(cnm=cnm).update(tname=tname)
                Test.objects.filter(cnm=cnm).update(paper=x)
            else:
                Test.objects.create(cnm=cnm,tname=tname,paper=x)
            if Verify.objects.filter(cnm_id=cnm):
                Verify.objects.filter(cnm_id=cnm).update(paper=x)
            else:
                Verify.objects.create(cnm_id=cnm,teaname=tname,paper=x)
        examname = request.POST.get('examname')
        examtime = request.POST.get('examtime')
        exampos = request.POST.get('exampos')
        examtip = request.POST.get('examtip')
        now=datetime.datetime.now()
        if Exam.objects.filter(examname=examname):
            Exam.objects.filter(examname=examname).update(examtime=examtime)
            Exam.objects.filter(examname=examname).update(exampos=exampos)
            Exam.objects.filter(examname=examname).update(examtip=examtip)
            Exam.objects.filter(examname=examname).update(etime=now)
        else:
            Exam.objects.create(examname=examname,examtime=examtime,exampos=exampos,examtip=examtip,etime=now)
        return HttpResponseRedirect('/teaIndex/test')
    else:
        tf=TestForm(tname)
    tn=Verify.objects.filter(teaname=tname)
    testshow=Test.objects.filter(tname=tname)
    return render(request,'test.html',{'tf':tf,'tn':tn,'testshow':testshow})

#下载【根据a标签中的下载链接】
def download(request):
    p= request.GET.get('name')
    fpath='media/'+str(p)
    print(fpath)
    def file_iterator(file=fpath, chunk_size=512):
            with open(file,'r',encoding='ISO-8859-1') as f:

                while True:
                    c = f.read(chunk_size)

                    if c:
                        yield c
                    else:
                        break
    str1=fpath
    str2=str1.split('/')[-1]
    response = StreamingHttpResponse(file_iterator(str1))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename=%s'%(str2)

    return response


def rlprint(request):
    userid = request.COOKIES.get('userid')
    cname = request.session.get('cname')
    tname = Tinfo.objects.get(email=userid).tname
    cnum = Tpcourse.objects.get(cname=cname, tname__tname=tname).id
    excelname='jxrili.xls'

    # print(excelname)
    ctime=Ctime.objects.filter(cnum_id=cnum).order_by('cnum__ctime__cweek')

    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename= %s'%(excelname)
    wb = xlwt.Workbook(encoding='utf-8')
    sheet = wb.add_sheet(u'教学日历')

    sheet.write(0,0,'周次')
    sheet.write(0,1,'学时数')
    sheet.write(0,2,'教学内容摘要')
    sheet.write(0,3,'实验、课程实习及其他')
    row=1
    for x in Ctime.objects.filter(cnum_id=cnum).order_by('id'):
        sheet.write(row,0,x.cweek)
        sheet.write(row,1,x.chours)
        sheet.write(row,2,x.ctext)
        sheet.write(row,3,x.catagory)
        row=row+1
    output=BytesIO()
    wb.save(output)
    output.seek(0)
    response.write(output.getvalue())
    return response


